import { defineStore } from 'pinia';
import goodsApi from '@/sheep/api/goods';
import _ from 'lodash';

const purchasing = defineStore({
  id: 'purchasing',
  state: () => ({
	loadStatus: '',
	current_page: 1,
	total: 1,
	last_page: 1,
	
    list: [], // 购物车列表
    selectedIds: [], // 已选列表
    isAllSelected: false, //是否全选
    cartSelectedTotalPrice: '0.00', // 选中项总金额
  }),
  getters: {
    totalPriceSelected: (state) => {
      let price = 0;
      if (!state.selectedIds.length) return price.toFixed(2);
      state.list.forEach((item) => {
        price += state.selectedIds.includes(item.id)
          ? ( _.isArray(item.price) ? Number(item.price[0]) : Number(item.price) ) * item.goods_num
          : 0;
      });
      return price.toFixed(2);
    },
  },
  actions: {
	loadmore() {
		if (this.loadStatus !== 'noMore') {
			this.getList(this.current_page + 1);
		}
	},
    // 获取购物车列表
    async getList(page = 1) {
	  this.current_page = page
      const res = await goodsApi.list({
		    type: 'card',
			list_rows: 10,
			keyword: this.keyword,
			page: this.current_page,
	  });
	  if(this.current_page === 1) {
		  this.list = []
	  }
      if (res.code === 1) {
        this.list = _.concat(this.list, res.data.data).map(i => ({...i, goods_num: 0}));
		this.total = res.data.total
		this.last_page = res.data.last_page
		
        if (res.data.current_page < res.data.last_page) {
          this.loadStatus = 'more';
        } else {
          this.loadStatus = 'noMore';
        }
      }
    },

    // 添加购物车
    async add(goodsInfo) {
      
    },
    
    // 更新购物车
    async update(goodsInfo) {
      
    },
    
    // 移除购物车
    async delete(ids) {
      
    },

    // 选择购物车商品
    selectSingle(goodsId) {
      if (!this.selectedIds.includes(goodsId)) {
        this.selectedIds.push(goodsId);
      } else {
        this.selectedIds.splice(this.selectedIds.indexOf(goodsId), 1);
      }
      this.isAllSelected = this.selectedIds.length === this.list.length;
    },

    // 全选
    selectAll(flag) {
      this.isAllSelected = flag;
      if (!flag) {
        this.selectedIds = [];
      } else {
        this.list.forEach((item) => {
			if(item.goods_num !== 0) {
				this.selectedIds.push(item.id);
			}
        });
      }
    },

    // 清空购物车
    emptyList() {
      this.list = [];
      this.selectedIds = [];
      this.isAllSelected = false;
      this.cartSelectedTotalPrice = '0.00';
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'purchasing-store',
      },
    ],
  },
});

export default purchasing;
